﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;

namespace BReusable
{
    
	public static class BHttpLib
	{

		private const string StrSneePostTest = "http://www.snee.com/xml/crud/posttest.cgi";



        public static HttpWebRequest ConstructHttpRequest(Uri location, String proxyLocation, int proxyPort)
		{
			return ConstructHttpRequest(location, new WebProxy(proxyLocation, proxyPort));
		}

        /// <summary>
        /// Get a request with no proxy
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        public static HttpWebRequest ConstructHttpRequest(this Uri location)
        {
            var result = (HttpWebRequest)WebRequest.Create(location);
            return result;
        }

		public static HttpWebRequest ConstructHttpRequest(Uri location, WebProxy proxy)
		{
			var result = (HttpWebRequest)WebRequest.Create(location);
            if (proxy != null)
            {
                result.Proxy = proxy;
                result.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
			return result;	
		}

        /// <summary>
        /// ContentType = "application/x-www-form-urlencoded"
        /// Method = "POST"
        /// </summary>
        /// <param name="location"></param>
        /// <param name="postData"></param>
        /// <param name="proxy">null for none</param>
        /// <returns></returns>
        public static HttpWebRequest ConstructHttpRequest(Uri location,
				IDictionary<string, string> postData,WebProxy proxy)
		{
            var result = ConstructHttpRequest(location, proxy);
			var sb = new StringBuilder();
			postData.ForEach(item => sb.Append("&" + item.Key + "=" + item.Value));
			var encoding=new ASCIIEncoding();
			var dataString=sb.ToString();
			var data = encoding.GetBytes(dataString);
			result.Method = "POST";
			result.KeepAlive = true;
			result.ContentType = "application/x-www-form-urlencoded";
			result.ContentLength = dataString.Length;
			Stream outStream=result.GetRequestStream();
			outStream.Write(data, 0, data.Length);
			outStream.Close();
			return result;
		}

        /// <summary>
        /// Method = "POST";
        /// ContentType = "application/xml";
        /// </summary>
        /// <param name="location"></param>
        /// <param name="proxy">null for none</param>
        /// <param name="xmlData"></param>
        /// <returns></returns>
        public static HttpWebRequest ConstructHttpRequestXml(Uri location, string xmlData, WebProxy proxy)
		{
			var result = ConstructHttpRequest(location, proxy);
			result.Method = "POST";
			result.ContentType = "application/xml";
			var encoding = new ASCIIEncoding();
			var data = encoding.GetBytes(xmlData);
			//result.ContentLength = xmlData.Length;
			Stream outStream = result.GetRequestStream();
			outStream.Write(data, 0, data.Length);
			outStream.Close();
			return result;
		}

		

		public static string GetSneePostTest(string proxyLocation, int proxyPort)
		{
			var proxy = new WebProxy(proxyLocation, proxyPort);
            var request = ConstructHttpRequest(new Uri(StrSneePostTest),
                new Dictionary<string, string> { { "fname", Environment.UserName }, { "lname", Environment.MachineName } }, proxy);
			return FromRequestGetResponseString(request);
		}

        /// <summary>
        /// Headers.Add("Authorization", "Basic " + encoded)
        /// </summary>
        /// <param name="location"></param>
        /// <param name="proxy"></param>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
		public static HttpWebRequest GetRequestWithProxyBasicAuthentication(Uri location, WebProxy proxy,string uid,string pwd )
		{
			var result = ConstructHttpRequest(location, proxy);
			
			var data=uid+":"+pwd;


			//var byteArray = new byte[data.Length];
			var encDataByte = Encoding.UTF8.GetBytes(data);
			var encoded = Convert.ToBase64String(encDataByte);
			result.Headers.Add("Authorization", "Basic " + encoded);
			return result;
		}


        public static string FromResponseGetString(this WebResponse response)
        {
            var sb = new StringBuilder();
            var buf = new byte[8192];
            int count;
            Stream resStream = response.GetResponseStream();
            do
            {
                count = resStream.Read(buf, 0, buf.Length);
                if (count != 0)
                {
                    var tempString = Encoding.ASCII.GetString(buf, 0, count);
                    sb.Append(tempString);
                }
            } while (count > 0);
            return sb.ToString();
        }

		public static String FromRequestGetResponseString(HttpWebRequest request)
		{
			
			var response = request.GetResponse();
            return response.FromResponseGetString();
		}

	}
}
